package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.utils.HtmlCleaner;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;

public class ZjNewsAnalyse implements AnalyseNews {

	//http://news.zj.com/detail/1453928.shtml
	//http://ent.zj.com/news/detail/2013-05-06/456478.html
	private static final String[] regex={
		"http://news.zj.com/detail/[0-9]*.shtml",
		"http://.*.zj.com/news/detail/[0-9]*-[0-9]*-[0-9]*/[0-9]*.html",
	};

	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}
		NewsMeta news=new NewsMeta();
		
		if (StringUtils.isBlank(news.getTitle())||news.getDate() == null) {
			String htmltxt=urlMeta.getHtml();
			Document doc=Jsoup.parse(htmltxt);
			String title=null;
			String content=null;
			Long date=null;
			title=doc.select("div.adetail_bt").text();
			content=HtmlCleaner.getContentHtml(url,doc.select("div.adetail_wz,div.adetail_font"));
			date=DateUtils.matchDate(doc.select("div.adetail_time").text());
			String text=doc.select("div.adetail_bj_s2 span").text();
			if(StringUtils.isNotBlank(text)){
				news.setAuthor(StringUtils.substringAfter(text, "来源："));
			}
			news.setUrl(url);
			news.setTitle(title);
			news.setContent(content);
			news.setDate(date);
		}
		if (StringUtils.isBlank(news.getTitle())||news.getDate() == null) {
		}
		return news;
	}

	public static void main(String[] args) {
		String url="http://news.zj.com/detail/1509409.shtml";
		ZjNewsAnalyse test=new ZjNewsAnalyse();
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(url);
		System.out.println(DoMainUtils.GetDomainName(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		NewsMeta parserHtml=test.parserHtml(meta);
		System.out.println(parserHtml);
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
